package cn.kiliter.dao;

import cn.kiliter.model.Order;
import cn.kiliter.model.OrderItem;
import cn.kiliter.model.Product;
import cn.kiliter.utils.C3P0Utils;
import cn.kiliter.utils.ManagerThreadLocal;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.ResultSetHandler;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class OrderDao {
    private QueryRunner qr=new QueryRunner();
    public void  saveOrder(Order order) throws SQLException {
        String sql="insert into orders values(?,?,?,?,?,?,?,?)";
        List<Object>list=new ArrayList<>();
        list.add(order.getId());
        list.add(order.getMoney());
        list.add(order.getReceiverAddress());
        list.add(order.getReceiverName());
        list.add(order.getReceiverPhone());
        list.add(order.getPaystate());
        list.add(order.getOrdertime());
        list.add(order.getUser().getId());
        qr.update(ManagerThreadLocal.getConnection(),sql,list.toArray());
    }
    public  List<Order> findOrderById(String  id) throws SQLException {
        String sql="select * from orders where user_id = ?";
        QueryRunner qr=new QueryRunner(C3P0Utils.getDataSource());
        return qr.query(sql,new BeanListHandler<Order>(Order.class),id);
    }

    public Order findOrderInfoById(String orderid) throws SQLException {
        QueryRunner qr=new QueryRunner(C3P0Utils.getDataSource());
        String sql="select * from orders where id = ?";
        Order order = qr.query(sql, new BeanHandler<Order>(Order.class),orderid);
        String sql2="select o.*,p.name,p.price from orderitem o ,products p where o.product_id = p.id and order_id = ? ";
        List<OrderItem> mItem=qr.query(sql2, new ResultSetHandler<List<OrderItem>>() {
            @Override
            public List<OrderItem> handle(ResultSet rs) throws SQLException {
                List<OrderItem> iItem=new ArrayList<>();
                while (rs.next()){
                    OrderItem item=new OrderItem();
                    item.setBuynum(rs.getInt("buynum"));
                    Product p=new Product();
                    p.setId(rs.getInt("product_id"));
                    p.setName(rs.getString("name"));
                    p.setPrice(rs.getDouble("price"));
                    item.setProduct(p);
                    iItem.add(item);
                }
                return iItem;
            }
        },orderid);

        order.setItems(mItem);
        return order;






    }

    public void updatepaystate(String id) throws SQLException {
        String sql="update orders set paystate = 1 where id = ?";
        QueryRunner qr=new QueryRunner(C3P0Utils.getDataSource());
        qr.update(sql,id);
    }
}
